﻿using Common;
using log4net;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Filters;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;

namespace Extensions.Swagger
{
    /// <summary>
    /// Swagger 启动服务
    /// </summary>
    public static class SwaggerSetup
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(SwaggerSetup));

        public static void AddSwaggerSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            var ApiName = AppSettings.app(new string[] { "Startup", "ApiName" });
            var version = AppSettings.app(new string[] { "Startup", "Version" });

            #region 默认
            //services.AddSwaggerGen(c =>
            //{
            //    c.SwaggerDoc("v1", new OpenApiInfo { Title = "CoreApiDome", Version = "v1" });
            //    // Jwt Bearer 认证，必须是 oauth2 （添加Authorization按钮）
            //    c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
            //    {
            //        Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}（注意两者之间是一个空格）\"",
            //        Name = "Authorization",//jwt默认的参数名称
            //        In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
            //        Type = SecuritySchemeType.ApiKey
            //    });
            //    // 开启加权小锁
            //    //c.OperationFilter<AddResponseHeadersFilter>();
            //    //c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
            //    // 在header中添加token，传递到后台
            //    c.OperationFilter<SecurityRequirementsOperationFilter>();
            //});
            #endregion


            #region 自定义
            services.AddSwaggerGen(c =>
            {
                //Swagger说明
                c.SwaggerDoc(version, new OpenApiInfo
                {
                    Version = version,
                    Title = $"{ApiName} 接口文档 - {RuntimeInformation.FrameworkDescription}",
                    Description = $"{ApiName} HTTP API " + version,
                    Contact = new OpenApiContact { Name = ApiName, Email = "1536624135@qq.com", Url = new Uri("http://106.55.168.52:6060/") },
                    License = new OpenApiLicense { Name = ApiName + " 官方文档", Url = new Uri("http://106.55.168.52:6060/") }
                });
                c.OrderActionsBy(o => o.RelativePath);

                try
                {
                    // 为 Swagger JSON and UI设置xml文档注释路径
                    var basePath = Path.Combine(AppContext.BaseDirectory, "BlogAPI.xml");//这个就是刚刚配置的xml文件名
                    c.IncludeXmlComments(basePath, true);//默认的第二个参数是false，这个是controller的注释，记得修改
                    var xmlPath = Path.Combine(AppContext.BaseDirectory, "Model.xml");//模型注释
                    c.IncludeXmlComments(xmlPath);
                }
                catch (Exception ex)
                {
                    log.Error("BlogAPI.xml和Model.xml 丢失，请检查并拷贝。\n" + ex.Message);
                }




                // Jwt Bearer 认证，必须是 oauth2
                c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}（注意两者之间是一个空格）\"",
                    Name = "Authorization",//jwt默认的参数名称
                    In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
                    Type = SecuritySchemeType.ApiKey
                });
                // 开启加权小锁
                c.OperationFilter<AddResponseHeadersFilter>();
                c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();

                // 在header中添加token，传递到后台
                c.OperationFilter<SecurityRequirementsOperationFilter>();

            });
            #endregion



        }
    }
}
